import { getToken, setToken, removeToken } from '@/utils/auth.js'
import { login, getUserinfo, unLogin } from '@/apis/user.js'
import { handleMessage } from '@/utils/utils'
import Vue from 'vue'
import router from '@/router'
import { Message, Loading } from 'element-ui'
// import router from '@/router/index.js'
// import Vue from 'vue'
const state = {
  token: getToken(), // token
  userinfo: {},
  // path: '/'
}

const mutations = {
  setToken(state, data) {
    state.token = data
  },
  setUserinfo(state, data) {
    state.userinfo = data
  },
  // setPath(state, data) {
  //   state.path = data
  // },
  // setAvatar(state, data) {
  //   state.userinfo.avatar = data
  // },
  // setNickname(state, data) {
  //   state.userinfo.nickname = data
  // }
}

const actions = {
  // 登录流程
  login({ commit }, userInfo) {
    const loadingInstance = Loading.service({
      fullscreen: true,
      lock: false,
    })
    login({ ...userInfo })
      .then(res => {
        setToken(res.data.token)
        commit('setToken', res.data.token)
        Vue.nextTick(() => {
          loadingInstance.close()
        })
        handleMessage(res.code, () => {
          Message({
            message: res.message,
            type: 'success'
          })
        })
        router.push('/')
      })
      .catch(() => {
        Vue.nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
          loadingInstance.close()
        })
      })
  },
  // 退出登录流程
  loginout() {
    let loadingInstance = Loading.service({
      fullscreen: true,
      lock: false,
    })
    unLogin()
      .then(res => {
        handleMessage(res.code, () => {
          removeToken()
          Message({
            message: res.message,
            type: 'success'
          })
          setTimeout(_ => {
            location.reload()
          }, 2000)
        })
        Vue.nextTick(() => {
          loadingInstance.close()
        })

      })
  },
  // 获取用户信息流程
  getuserinfo({ commit }) {
    getUserinfo().then(res => {
      commit('setUserinfo', res.data)
    })
  },
  //   // 注册流程
  //   register({ commit }, userInfo) {
  //     let { username, password } = userInfo
  //   },
  //   // 改变路径
  //   changePath({ commit }, index) {
  //     if (Number(index) == 1) {
  //       commit('setPath', '/user')
  //     } else if (Number(index) == 0) {
  //       commit('setPath', '/')
  //     } else if (Number(index) == 2) {
  //       commit('setPath', '/form')
  //     }
  //     else if (Number(index) == 3) {
  //       commit('setPath', '/daili')
  //     }
  //     else if (Number(index) == 4) {
  //       commit('setPath', '/more')
  //     }
  //   }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}


